from selenium import webdriver
from datetime import datetime
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as  EC

class BasePage:
    def __init__(self):
        self.driver=webdriver.Chrome()

    def open(self,url):
        self.driver.get(url)

    def get_element(self,locator,doc):
        ele=None
        print('开始进行元素%s的定位'%str(locator))
        try:
            res=self.wait(locator)
            if res:
                start_time=datetime.now()
                ele=self.driver.find_element(*locator)
                end_time=datetime.now()
                times=(end_time-start_time).seconds
                print('元素%s的定位成功，用时%d秒'%(str(locator),times))

        except Exception as e:
            print('元素%s的定位失败'%str(locator))
            self.get_screen_shoot(doc)

            return ele
    def get_screen_shoot(self,filename):
            path='./rest_result/screenshot/'+filename+'png'
            self.driver.get_screenshot_as_file(path)

    def input_text(self,locator,doc,text):
        ele=self.get_element(locator,doc)
        if ele is None:
            print('元素为空,不能进行输入操作！')
        else:
            ele.send_keys(text)

    def click_element(self,locator,doc):
        ele=self.get_element(locator,doc)
        if ele is None:
            print('元素为空,不能进行点击操作！')
        else:
            ele.click()


    def get_element_text(self,locator,doc):
        ele=self.get_element(locator,doc)
        if ele is None:
            print('元素为空，不能获取元素的文本值！')
        else:
            return ele.text

    def wait(self,locator,times=10,poll=0.5):
        print('开始等待%s'%str(locator))

        try:
            WebDriverWait(self.driver,times,poll).until(EC.visibility_of_element_located(locator))
            print('元素%s等待成功' % str(locator))
            return True
        except Exception as e:
            print('元素%s等待失败' % str(locator))
            return False














